/*
 * 用法:
 * let ss = new Storage('', 'sessionStorage')
 * ss.set('name',{a:'11'})
 * ss.get('name')
 * ss.remove('name')
 * ss.clear()
 */
const isSupport = !!(function () {
  let _localStorage
  try {
    _localStorage = localStorage
    _localStorage._ = 0
    return _localStorage._
  } catch (e) {}
})()
const sham = {
  localStorage: {},
  sessionStorage: {},
}
const Storage = (function () {
  function Storage(namespace, type) {
    if (namespace === '') {
      namespace = ''
    }
    if (type === '') {
      type = ''
    }
    this._s = isSupport ? window[type] : sham[type]
    this._t = type
    this._ns = namespace ? namespace + '_' : ''
  }
  Storage.prototype.get = function (key) {
    key = this._ns + key
    let ret
    try {
      ret = JSON.parse(this._s[key])
    } catch (e) {
      ret = sham[this._t][key]
    }
    return ret == null ? null : ret
  }
  Storage.prototype.set = function (key, value) {
    key = this._ns + key
    try {
      this._s[key] = JSON.stringify(value)
    } catch (e) {
      sham[this._t][key] = value
      this.clear(true)
    }
  }
  Storage.prototype.remove = function (key) {
    key = this._ns + key
    try {
      this._s.removeItem(key)
    } catch (e) {
      delete sham[this._t][key]
    }
  }
  Storage.prototype.clear = function (_donotClearSham) {
    if (_donotClearSham === '') {
      _donotClearSham = false
    }
    try {
      this._s.clear()
    } catch (err) {
      console.log(err)
      !_donotClearSham && (sham[this._t] = {})
    }
  }
  Storage.isSupport = isSupport
  return Storage
})()
export default Storage
